//
//  OpenDoc.m
//  YTwallet
//
//  Created by hadrlog on 2019/5/17.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "OpenDoc.h"

@implementation OpenDoc
//是否下载还是打开文件

- (void)downloadPDF:(NSString *)downloadUrl{
    
    NSArray *array = [downloadUrl componentsSeparatedByString:@"/"]; //从字符/中分隔成多个元素的数组
    
    NSString *file = [array lastObject];
    
    
    
    if ([self isFileExist:file]) {
        
        
        
        //获取Documents 下的文件路径
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *path = [paths objectAtIndex:0];
        
        NSString *pathString = [path stringByAppendingFormat:@"/%@",file];
        
        NSLog(@"path:%@", pathString);
        

        [self.delegate rebackDocPath:pathString];
        
    }else{
        
        //从新下载
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *path = [paths objectAtIndex:0];
        NSString *pathString = [path stringByAppendingFormat:@"/%@",file];
        [self downloadFile:downloadUrl tofile:pathString];
        
    }
    
    
    
}
//////////    第三步

//下载PDF

- (void)downloadFile:(NSString *)downLoadUrl tofile:(NSString *)file{
    __weak typeof(self)weakSelf = self;
    [[ETONEHttpClient sharedInstance]downloadDocFromUrl:downLoadUrl Storefile:file finish:^(BOOL finish) {
        if (finish) {
            [weakSelf.delegate rebackDocPath:file];
        }else{
            
            
        }
    }];
    
    
    
}
#pragma mark      第二步    判断沙盒中是否存在此文件



-(BOOL) isFileExist:(NSString *)fileName

{
    
    //获取Documents 下的文件路径
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *path = [paths objectAtIndex:0];
    
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL result = [fileManager fileExistsAtPath:filePath];
    
    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    
    return result;
    
}


@end
